package com.worldtolearn.webservices;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

@Path("/total")
public class TaxChangeService implements ITaxChanceService {

	Map<String, Double> changes = null;
	Map<String, String> currencies = null;
	List<String> allCountries = null;

	@Override
	@GET
	@Path("/price/{country}")
	public double getTaxChangeCoefficient(
			@PathParam("country") String countryParam) {
		double taxCoeff = 1.0;
		try {
			URL url = new URL(
					"http://localhost:8080/AWorldToLearn/rest/tax/rate/"
							+ countryParam);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.setRequestProperty("Accept", "application/json");

			if (conn.getResponseCode() != 200) {
				throw new RuntimeException("Failed : HTTP error code : "
						+ conn.getResponseCode());
			}

			BufferedReader reader = new BufferedReader(new InputStreamReader(
					conn.getInputStream()));
			String output;

			if ((output = reader.readLine()) != null) {
				taxCoeff = Double.parseDouble(output);
			}

			conn.disconnect();

			if (changes == null || currencies == null) {
				initialize();
			}

			Double change = changes.get(countryParam);
			if (change == null)
				change = 1.0;

			return change * taxCoeff;

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return 1.0;
	}

	@Override
	@GET
	@Path("/currency/{country}")
	public String getCurrency(@PathParam("country") String countryParam) {
		if (changes == null || currencies == null) {
			initialize();
		}
		String retour = currencies.get(countryParam);
		if (retour != null)
			return retour;

		return "EUR";
	}

	private void initialize() {
		JSONParser parser = new JSONParser();
		changes = new HashMap<String, Double>();
		currencies = new HashMap<String, String>();
		allCountries = new ArrayList<String>();
		try {
			URL url = new URL(
					"http://localhost:8080/changeservice/change/allchanges");
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setDoOutput(true);
			conn.setRequestMethod("GET");
			conn.setRequestProperty("Content-Type", "application/json");

			if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
				System.out.println("conn.getResponseCode() : "
						+ conn.getResponseCode());
				System.out.println("HttpURLConnection.HTTP_CREATED: "
						+ HttpURLConnection.HTTP_CREATED);
				throw new RuntimeException("Failed : HTTP error code : "
						+ conn.getResponseCode());
			}

			BufferedReader br = new BufferedReader(new InputStreamReader(
					(conn.getInputStream())));

			String output;
			System.out.println("Output from Server .... \n");
			while ((output = br.readLine()) != null) {

				Object obj = parser.parse(output);

				JSONObject jsonObject = (JSONObject) obj;
				// loop array
				JSONArray chl = (JSONArray) jsonObject.get("changeList");
				System.out
						.println("*****************************************************");
				for (Object obj2 : chl) {
					JSONObject jsonObject2 = (JSONObject) obj2;
					String country = (String) jsonObject2.get("country");
					allCountries.add(country);
					System.out.println("country : " + country);
					String currency = (String) jsonObject2.get("currency");
					System.out.println("currency : " + currency);
					Double change = (Double) jsonObject2.get("rate");
					System.out.println("rate : " + change);
					changes.put(country, change);
					currencies.put(country, currency);
				}
				System.out
						.println("*****************************************************");

			}

			conn.disconnect();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {

			e.printStackTrace();

		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	@GET
	@Path("/change/{country}")
	public double getChangeOnlyCoeff(@PathParam("country") String countryParam) {
		if (changes == null || currencies == null) {
			initialize();
		}
		Double change = changes.get(countryParam);
		if (change != null)
			return change;
		return 1;
	}

	@Override
	@GET
	@Path("/allcountries/")
	@Produces("application/json")
	public String getAllCountries() {
		if (changes == null || currencies == null) {
			initialize();
		}
		String retour = " [ ";
		for (String country : allCountries) {
			retour += "{\"country\":\"" + country + "\"}" + ",";
		}
		retour = retour.substring(0, retour.length() - 1);
		retour += "]";
		return retour;
	}
}
